﻿using Fuse8.DomainFramework.BusinessService;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.GlobalizationFramework.Domain;
using Fuse8.GlobalizationFramework.Domain.Commands;
using Fuse8.GlobalizationFramework.Infrastructure;
using Microsoft.Practices.Unity;

namespace Fuse8.GlobalizationFramework.BusinessServices
{
    /// <summary>
    /// Provides methods for working with resources
    /// </summary>
    public class ResourceService
    {
        private static readonly BusinessServiceFacade<Resource, int> businessService;

        static ResourceService()
        {
            Policy.InitDependicies();
            businessService = new BusinessServiceFacade<Resource, int>();
        }        

        /// <summary>
        /// Finds resource value by specified key and current culture
        /// </summary>
        /// <param name="key">Resource key</param>
        /// <param name="defaultValue">Default value</param>
        /// <param name="addInDatabase">Specifies if it is needed to add defautl value to database</param>
        /// <returns></returns>
        public static string FindValue(string key, string defaultValue = null, bool addInDatabase = true)
        {
            string value = defaultValue;
            var factory = DependencyServiceLocator.Current.GetInstance<IResourceCommandFactory>();
            var command = factory.GetCommand<ResourceByKeyAndLocale>();
            command.Key = key;
            GlobalizationMediator.InitCulture(command);

            var resource = businessService.FindOneByCommand(command);
            if (resource != null)
            {
                value = resource.Value;
            }
            else if (addInDatabase && defaultValue != null)
            {
                resource = new Resource() {Key = key, Value = defaultValue};
                GlobalizationMediator.InitCulture(resource);
                businessService.Add(resource);
            }

            return FormatValue(value, key);            
        }

        /// <summary>
        /// Checks if specified value is default generated
        /// </summary>
        /// <param name="value">Value to check</param>
        /// <param name="key">Key of this value</param>
        /// <returns></returns>
        public static bool IsDefaultValue(string value, string key)
        {
            return value.Equals(GetDeafultValue(key));
        }

        private static string FormatValue(string value, string key)
        {
            return value ?? GetDeafultValue(key);
        }

        private static string GetDeafultValue(string key)
        {
            return string.Format("*DEFAULT {0}*", key);
        }
    }
}